from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.models import SKU, GoodsCategory, SPUSpecification
from meiduo_admin.serializers.skus import SKUGoodsSerializer
from meiduo_admin.serializers.skus import SPUSpecificationSerializer
from meiduo_admin.utils import PageNum


class SKUGoodsView(ModelViewSet):
    """
    sku表增删改查
    """
    # 指定查询集
    queryset = SKU.objects.all()
    # 指定序列化器
    serializer_class = SKUGoodsSerializer
    # 指定分页器
    pagination_class = PageNum
    # 指定管理员权限
    permission_classes = [IsAdminUser]

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword is None or keyword == '':
            return SKU.objects.all()
        else:
            return SKU.objects.filter(name__contains=keyword)

    # 获取三级分类信息
    @action(methods=['get'], detail=False)
    def categories(self, request):
        data = GoodsCategory.objects.filter(subs=None)
        ser = SKUGoodsSerializer(data, many=True)
        return Response(ser.data)

    # 获取规格信息
    def specs(self, request, pk):
        # 根据spu_id查询符合条件的规格信息
        data = SPUSpecification.objects.filter(spu_id=pk)
        ser = SPUSpecificationSerializer(data, many=True)
        return Response(ser.data)
